/**
 * Still very WIP, uses a lot of CPU.
 * DO NOT USE
 * */
using UnityEngine;
using System.Collections;
using System.Threading;

public class LoopThread {
	
	public float[] samples;
	
	
}

[System.Serializable]
public class PlayerMicrophoneTrigger : MonoBehaviour {
	
	public AudioClip scarySound;
	public AudioSource scarySoundSource;
	
	private float[] samples;
	
	private bool quiet = false;
	private float beenQuietForSec = 0.0f;
	
	// Use this for initialization
	void Start () {
		Debug.Log("Starting recording.");
		audio.clip = Microphone.Start(Microphone.devices[0], true, 1, 44100);
   		//audio.Play();
		Debug.Log("Recording ended!");
		gatherSampleData();
	}
	
	void LoopThroughSamples() {
		Debug.Log("Thread started.");
		foreach (float f in samples) {
			Debug.Log("Sample: " + f);	
		}
		Debug.Log("Thread ended.");
	}
	
	// Update is called once per frame
	void Update () {
		if (true) {
			Debug.Log("Starting recording.");
			Microphone.Start(Microphone.devices[0], true, 1, 44100);
			Debug.Log("Recording ended!");
			Debug.Log("Gathering sample data.");
			gatherSampleData();
			Debug.Log("Done gathering sample data.");
						
			if (quiet) {
				beenQuietForSec += Time.time;
				int quietFor = (int) beenQuietForSec;
				//Debug.Log("You have been quiet for: " + quietFor + 	" seconds");
				if (beenQuietForSec > 30000	&& !scarySoundSource.isPlaying)
					scarySoundSource.PlayOneShot(scarySound);
			} else {
				beenQuietForSec = 0.0f;
			}
		}
	}
	
	void gatherSampleData() {
		samples = new float[audio.clip.samples * audio.clip.channels];
		audio.clip.GetData(samples, 0);
		
		float sample = samples[(44100 / 2)];
		
		//LoopThroughSamples();
		Debug.Log ("Sample " + (44100 / 2) + ": " + sample);
		
		if (sample > 0.009	) {
			Debug.Log("You made a medium loud noise: " + sample);
			quiet = false;
		} else {
			Debug.Log("You are quiet.");
			quiet = true;
		}
	}
	
	void OnGUI() {
		
	}
}
